package com.lei.springbootpractice.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@Configuration
public class SessionConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SessionInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/register", "/css/**", "/js/**", "/images/**", "/h2-console/**");
    }

    public static class SessionInterceptor implements HandlerInterceptor {
        
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession(false);
            String requestURI = request.getRequestURI();
            
            // 如果是登录页面，直接放行
            if (requestURI.equals("/login") || requestURI.equals("/register") || requestURI.equals("/")) {
                return true;
            }
            
            // 检查是否已登录
            if (session == null || session.getAttribute("loggedInUser") == null) {
                response.sendRedirect("/login");
                return false;
            }
            
            // 添加会话信息到请求属性中，方便调试
            String userId = (String) session.getAttribute("loggedInUser");
            String userRole = (String) session.getAttribute("userRole");
            request.setAttribute("currentUserId", userId);
            request.setAttribute("currentUserRole", userRole);
            
            return true;
        }
    }
} 